from app.models import Job
import web
import jobs
import urllib
import consts
import StringIO

class Page(object):
  """ Subclasses of this are automatically added by application.py to urls """
  url = ''

class Progress(Page):
  # url = '/'
  def GET(self):
    i = web.input('key')
    urllib.urlencode({'key' : i.key })
    return """
    
    """

class DoJob(Page):    
  url = '/'
  def GET(self):
    i = web.input('key')
    job = Job.get(i.key)
    handler = getattr(jobs, job.handler)
    ret = handler(job)
    if not ret:
      return "Try again later."
      
    if hasattr(ret, "seek") and hasattr(ret, "read"):
      ret.seek(0)
      return str(ret.read())
    
    if isinstance(ret, basestring):
      ret = ret.replace('$APP_ENGINE_URL', consts.appengine_host)
    if not ret.startswith('http'):
      ret = "http://" + ret
      
    raise web.seeother(ret)
  
  def POST(self):
    i = web.input(data=[])
    return "SUCCESS %s" % i.data
